//
//  BillView.swift
//  bill
//
//  Created by Eudon on 2025/6/18.
//

import SwiftUI

// 账单页面视图
struct BillView: View {
    @ObservedObject var store: TransactionStore
    @State private var selectedIndex: Int? = nil
    @State private var collapsedDates: Set<String> = []
    
    // 根据日期范围筛选交易
    private var filteredTransactions: [Transaction] {
        let start = store.startDate
        let end = store.endDate
        return store.filteredTransactions(from: start, to: end)
    }
    
    // 计算总余额
    private var totalBalance: Double {
        filteredTransactions.reduce(0) { $0 + (($1.type == .income) ? $1.amount : -$1.amount) }
    }
    
    // 计算收入
    private var monthlyIncome: Double {
        filteredTransactions.filter { $0.type == .income }.reduce(0) { $0 + $1.amount }
    }
    
    // 计算支出
    private var monthlyExpense: Double {
        filteredTransactions.filter { $0.type == .expense }.reduce(0) { $0 + $1.amount }
    }
    
    // 获取支出分类数据
    private var expenseCategories: [(value: Double, color: Color, label: String)] {
        var categoryTotals: [String: Double] = [:]
        for transaction in filteredTransactions where transaction.type == .expense {
            categoryTotals[transaction.category, default: 0] += transaction.amount
        }
        
        let colors: [Color] = [
            Color(red: 0.2, green: 0.6, blue: 0.9),   // GitHub Blue
            Color(red: 0.9, green: 0.3, blue: 0.3),   // GitHub Red
            Color(red: 0.3, green: 0.8, blue: 0.4),   // GitHub Green
            Color(red: 0.9, green: 0.6, blue: 0.2),   // GitHub Orange
            Color(red: 0.7, green: 0.4, blue: 0.9),   // GitHub Purple
            Color(red: 0.9, green: 0.4, blue: 0.7),   // GitHub Pink
            Color(red: 0.9, green: 0.8, blue: 0.2),   // GitHub Yellow
            Color(red: 0.4, green: 0.8, blue: 0.8)    // GitHub Teal
        ]
        
        return categoryTotals.enumerated().map { (index, element) in
            (value: element.value, 
             color: colors[index % colors.count], 
             label: element.key)
        }.sorted { $0.value > $1.value }
    }
    
    // 按日期分组
    private var groupedTransactions: [String: [Transaction]] {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy年MM月dd日"
        
        var groups: [String: [Transaction]] = [:]
        for transaction in filteredTransactions {
            let dateString = dateFormatter.string(from: transaction.date)
            if groups[dateString] == nil {
                groups[dateString] = []
            }
            groups[dateString]?.append(transaction)
        }
        return groups
    }
    
    // 切换折叠状态
    private func toggleCollapse(for date: String) {
        if collapsedDates.contains(date) {
            collapsedDates.remove(date)
        } else {
            collapsedDates.insert(date)
        }
    }
    
    // 计算日期组的总金额
    private func totalAmount(for transactions: [Transaction]) -> Double {
        transactions.reduce(0) { $0 + (($1.type == .income) ? $1.amount : -$1.amount) }
    }
    
    var body: some View {
        ScrollView {
            VStack(spacing: 24) {
                // 日期范围选择器
                DateRangePicker(startDate: Binding(
                    get: { store.startDate },
                    set: { store.updateDateRange(start: $0, end: store.endDate) }
                ), endDate: Binding(
                    get: { store.endDate },
                    set: { store.updateDateRange(start: store.startDate, end: $0) }
                ))
                .padding(.horizontal, 20)
                
                // 总余额模块
                VStack(spacing: 20) {
                    Text("总余额")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(Color(.secondaryLabel))
                    Text("¥\(totalBalance, specifier: "%.2f")")
                        .font(.system(size: 42, weight: .bold))
                        .foregroundColor(Color(.label))
                        .padding(.top, 4)
                    
                    HStack(spacing: 40) {
                        VStack(spacing: 8) {
                            Text("收入")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                            Text("¥\(monthlyIncome, specifier: "%.2f")")
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundColor(Color(red: 0.3, green: 0.8, blue: 0.4))
                        }
                        
                        Divider()
                            .frame(height: 50)
                            .background(Color(.separator))
                        
                        VStack(spacing: 8) {
                            Text("支出")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                            Text("¥\(monthlyExpense, specifier: "%.2f")")
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundColor(Color(red: 0.9, green: 0.3, blue: 0.3))
                        }
                    }
                    .padding(.top, 8)
                }
                .padding(.horizontal, 24)
                .padding(.vertical, 28)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(Color(.systemBackground))
                        .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2)
                )
                .padding(.horizontal, 20)
                
                // 支出分布饼图
                if !expenseCategories.isEmpty {
                    VStack(spacing: 0) {
                        HStack {
                            Text("支出分布")
                                .font(.system(size: 18, weight: .semibold))
                                .foregroundColor(Color(.label))
                            Spacer()
                        }
                        .padding(.horizontal, 24)
                        .padding(.top, 24)
                        
                        PieChartView(data: expenseCategories, selectedIndex: $selectedIndex)
                            .padding(.horizontal, 20)
                            .padding(.vertical, 16)
                    }
                    .background(
                        RoundedRectangle(cornerRadius: 16)
                            .fill(Color(.systemBackground))
                            .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2)
                    )
                    .padding(.horizontal, 20)
                }
                
                // 交易记录区
                VStack(alignment: .leading, spacing: 20) {
                    HStack {
                        Text("账单明细")
                            .font(.system(size: 18, weight: .semibold))
                            .foregroundColor(Color(.label))
                        Spacer()
                    }
                    .padding(.horizontal, 20)
                    
                    if groupedTransactions.isEmpty {
                        VStack(spacing: 16) {
                            Image(systemName: "doc.text")
                                .font(.system(size: 48))
                                .foregroundColor(Color(.tertiaryLabel))
                            Text("该时间段内暂无交易记录")
                                .font(.system(size: 16, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 40)
                    } else {
                        VStack(spacing: 16) {
                            ForEach(groupedTransactions.keys.sorted().reversed(), id: \.self) { date in
                                VStack(alignment: .leading, spacing: 0) {
                                    // 日期标题栏（可点击）
                                    Button(action: {
                                        withAnimation(.easeInOut(duration: 0.25)) {
                                            toggleCollapse(for: date)
                                        }
                                    }) {
                                        HStack {
                                            VStack(alignment: .leading, spacing: 4) {
                                                Text(date)
                                                    .font(.system(size: 18, weight: .bold))
                                                    .foregroundColor(Color(.label))
                                                
                                                let transactions = groupedTransactions[date]!
                                                let total = totalAmount(for: transactions)
                                                Text("¥\(total, specifier: "%.2f")")
                                                    .font(.system(size: 16, weight: .semibold))
                                                    .foregroundColor(total >= 0 ? Color(red: 0.3, green: 0.8, blue: 0.4) : Color(red: 0.9, green: 0.3, blue: 0.3))
                                            }
                                            
                                            Spacer()
                                            
                                            // 交易数量
                                            Text("\(groupedTransactions[date]!.count)笔")
                                                .font(.system(size: 14, weight: .medium))
                                                .foregroundColor(Color(.secondaryLabel))
                                                .padding(.horizontal, 12)
                                                .padding(.vertical, 6)
                                                .background(
                                                    RoundedRectangle(cornerRadius: 8)
                                                        .fill(Color(.tertiarySystemBackground))
                                                )
                                            
                                            // 折叠图标
                                            Image(systemName: collapsedDates.contains(date) ? "chevron.right" : "chevron.down")
                                                .font(.system(size: 16, weight: .semibold))
                                                .foregroundColor(Color(.systemBlue))
                                                .frame(width: 24, height: 24)
                                                .background(
                                                    Circle()
                                                        .fill(Color(.systemBlue).opacity(0.1))
                                                )
                                        }
                                        .padding(.horizontal, 20)
                                        .padding(.vertical, 20)
                                        .background(
                                            RoundedRectangle(cornerRadius: 16)
                                                .fill(Color(.systemBackground))
                                                .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2)
                                        )
                                        .padding(.horizontal, 20)
                                    }
                                    .buttonStyle(PlainButtonStyle())
                                    
                                    // 交易明细（可折叠）
                                    if !collapsedDates.contains(date) {
                                        VStack(spacing: 12) {
                                            ForEach(groupedTransactions[date]!) { transaction in
                                                NavigationLink(destination: TransactionDetailView(transaction: transaction)) {
                                                    HStack(spacing: 16) {
                                                        // 类别图标
                                                        ZStack {
                                                            Circle()
                                                                .fill(transaction.type == .income ? 
                                                                      Color(red: 0.3, green: 0.8, blue: 0.4).opacity(0.15) : 
                                                                      Color(red: 0.9, green: 0.3, blue: 0.3).opacity(0.15))
                                                                .frame(width: 44, height: 44)
                                                            
                                                            Text(transaction.type == .income ? "入" : "出")
                                                                .font(.system(size: 18, weight: .bold))
                                                                .foregroundColor(transaction.type == .income ? 
                                                                               Color(red: 0.3, green: 0.8, blue: 0.4) : 
                                                                               Color(red: 0.9, green: 0.3, blue: 0.3))
                                                        }
                                                        
                                                        VStack(alignment: .leading, spacing: 4) {
                                                            Text(transaction.category)
                                                                .font(.system(size: 16, weight: .medium))
                                                                .foregroundColor(Color(.label))
                                                            if let note = transaction.note {
                                                                Text(note)
                                                                    .font(.system(size: 14))
                                                                    .foregroundColor(Color(.secondaryLabel))
                                                            }
                                                        }
                                                        
                                                        Spacer()
                                                        
                                                        Text(transaction.type == .income ? "+¥\(transaction.amount, specifier: "%.2f")" : "-¥\(transaction.amount, specifier: "%.2f")")
                                                            .font(.system(size: 16, weight: .semibold))
                                                            .foregroundColor(transaction.type == .income ? 
                                                                           Color(red: 0.3, green: 0.8, blue: 0.4) : 
                                                                           Color(red: 0.9, green: 0.3, blue: 0.3))
                                                    }
                                                    .padding(.horizontal, 20)
                                                    .padding(.vertical, 16)
                                                    .background(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .fill(Color(.systemBackground))
                                                            .shadow(color: Color.black.opacity(0.04), radius: 4, x: 0, y: 1)
                                                    )
                                                    .padding(.horizontal, 20)
                                                }
                                                .buttonStyle(PlainButtonStyle())
                                            }
                                        }
                                        .padding(.top, 8)
                                    }
                                }
                            }
                        }
                    }
                }
                .padding(.top, 8)
            }
            .padding(.vertical, 20)
        }
        .background(Color(.systemGroupedBackground))
        .navigationTitle("账单")
        .navigationBarTitleDisplayMode(.large)
    }
}

#Preview {
    NavigationView {
        BillView(store: TransactionStore())
    }
} 